import { tryOnMounted, tryOnUnmounted } from '@vc/utils';
import { useDebounceFn } from '..';

interface WindowSizeOptions {
  once?: boolean;
  immediate?: boolean;
  listenerOptions?: AddEventListenerOptions | boolean;
}

/**
 * @description window 发生 resize 事件监听
 * @author wfd
 * @date 2022/11/14 20:20
 * @example
 * @param {AnyFunction<T>} fn
 * @param {number} wait
 * @param {WindowSizeOptions} options
 * @returns {[(() => void), (() => void)]}
 */
export const useWindowResize = <T> (fn: AnyFunction<T>, wait = 150,
  options?: WindowSizeOptions) => {
  let handler = () => {
    fn();
  };
  const handleSize = useDebounceFn(handler, wait);
  handler = handleSize;
  
  const start = () => {
    if (options && options.immediate) {
      handler();
    }
    window.addEventListener('resize', handler);
  };
  
  const stop = () => {
    window.removeEventListener('resize', handler);
  };
  
  tryOnMounted(() => {
    start();
  });
  
  tryOnUnmounted(() => {
    stop();
  });
  return [start, stop];
};
